<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工人管理系统 - 主页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background: #f5f6fa;
            min-height: 100vh;
        }

        /* 头部样式 */
        .header {
            background: linear-gradient(135deg, #3498db, #2c3e50);
            color: white;
            padding: 1rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
        }

        .logo h1 {
            font-size: 1.8rem;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .logout-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .logout-btn:hover {
            background: rgba(255,255,255,0.3);
        }

        /* 主内容区 */
        .main-container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }

        /* 操作栏 */
        .action-bar {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .search-box {
            display: flex;
            gap: 1rem;
        }

        .search-input {
            padding: 0.5rem 1rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 300px;
        }

        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background: #2980b9;
        }

        .btn-success {
            background: #27ae60;
            color: white;
        }

        .btn-success:hover {
            background: #229954;
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background: #c0392b;
        }

        /* 表格样式 */
        .workers-table {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            position: relative;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            border-bottom: 1px solid #eee;
            padding-bottom: 1rem;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #7f8c8d;
        }

        .close-btn:hover {
            color: #34495e;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .form-group input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
            transition: border 0.3s;
        }

        .form-group input:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 1.5rem;
            padding-top: 1rem;
            border-top: 1px solid #eee;
        }

        /* 消息提示 */
        .message {
            padding: 1rem;
            border-radius: 4px;
            margin-bottom: 1rem;
            text-align: center;
            display: none;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .message.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        /* 加载动画 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 2rem;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 2rem;
            color: #7f8c8d;
        }
    </style>
</head>
<body>
<!-- 头部 -->
<header class="header">
    <div class="header-content">
        <div class="logo">
            <h1>工人管理系统</h1>
        </div>
        <div class="user-info">
            <span id="currentUser">欢迎，管理员</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<div class="main-container">
    <!-- 操作栏 -->
    <div class="action-bar">
        <div class="search-box">
            <input type="text" id="searchInput" class="search-input" placeholder="搜索工人姓名或教室...">
            <button class="btn btn-primary" onclick="searchWorkers()">搜索</button>
            <button class="btn" onclick="clearSearch()">重置</button>
        </div>
        <button class="btn btn-success" onclick="openAddModal()">添加工人</button>
    </div>

    <!-- 消息提示 -->
    <div id="message" class="message"></div>

    <!-- 工人列表 -->
    <div class="workers-table">
        <table>
            <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>教室</th>
                <th>老师</th>
                <th>日期</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="workersTableBody">
            <tr>
                <td colspan="6" class="loading">
                    <div class="spinner"></div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- 添加/编辑工人模态框 -->
<div id="workerModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">添加工人</h3>
            <button class="close-btn" onclick="closeModal()">&times;</button>
        </div>
        <form id="workerForm">
            <input type="hidden" id="workerId">
            <div class="form-group">
                <label for="name">姓名</label>
                <input type="text" id="name" required>
            </div>
            <div class="form-group">
                <label for="classroom">教室号</label>
                <input type="number" id="classroom" required>
            </div>
            <div class="form-group">
                <label for="teacher">老师</label>
                <input type="text" id="teacher" required>
            </div>
            <div class="form-group">
                <label for="date">日期</label>
                <input type="date" id="date" required>
            </div>
            <div class="form-actions">
                <button type="button" class="btn" onclick="closeModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>
<script>
let workers = [];
let currentEditingId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
console.log('页面加载完成，开始初始化...');
loadWorkers();
document.getElementById('workerForm').addEventListener('submit', handleWorkerSubmit);
});

// 加载工人列表
async function loadWorkers() {
try {
showLoading();
console.log('开始加载工人数据...');

const response = await fetch('/workers');
console.log('响应状态:', response.status);

if (!response.ok) {
throw new Error(`HTTP错误! 状态: ${response.status}`);
}

const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error(`期望JSON响应，但收到: ${contentType}`);
}

workers = await response.json();
console.log('加载到的工人数据:', workers);
renderWorkersTable(workers);
hideLoading();

} catch (error) {
console.error('加载工人数据错误:', error);
showMessage('加载数据失败: ' + error.message, 'error');
hideLoading();
}
}

// 渲染工人表格
function renderWorkersTable(workersList) {
const tbody = document.getElementById('workersTableBody');

if (!workersList || workersList.length === 0) {
tbody.innerHTML = `
<tr>
    <td colspan="6" class="empty-state">
        暂无工人数据，点击"添加工人"按钮添加
    </td>
</tr>
`;
return;
}

tbody.innerHTML = workersList.map(worker => `
<tr>
    <td>${worker.id || ''}</td>
    <td>${worker.name || ''}</td>
    <td>${worker.classroom || ''}</td>
    <td>${worker.teacher || ''}</td>
    <td>${formatDate(worker.date)}</td>
    <td class="action-buttons">
        <button class="btn btn-primary" onclick="editWorker(${worker.id})">编辑</button>
        <button class="btn btn-danger" onclick="deleteWorker(${worker.id})">删除</button>
    </td>
</tr>
`).join('');
}

// 处理工人表单提交
async function handleWorkerSubmit(event) {
event.preventDefault();
console.log('处理表单提交...');

const formData = {
name: document.getElementById('name').value.trim(),
classroom: parseInt(document.getElementById('classroom').value) || 0,
teacher: document.getElementById('teacher').value.trim(),
date: document.getElementById('date').value
};

// 验证必填字段
if (!formData.name || !formData.teacher) {
showMessage('姓名和老师字段不能为空', 'error');
return;
}

try {
let url = '/workers';
let method = 'POST';

if (currentEditingId) {
url = `/workers/${currentEditingId}`;
method = 'PUT';
}

console.log('发送请求:', { url, method, formData });

const response = await fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
});

console.log('响应状态:', response.status);

if (!response.ok) {
const errorText = await response.text();
throw new Error(`请求失败: ${response.status} - ${errorText}`);
}

const result = await response.json();
console.log('操作成功:', result);

closeModal();
showMessage(`工人${currentEditingId ? '更新' : '添加'}成功`, 'success');
loadWorkers();

} catch (error) {
console.error('保存工人错误:', error);
showMessage('操作失败: ' + error.message, 'error');
}
}

// 添加工人
function openAddModal() {
currentEditingId = null;
document.getElementById('modalTitle').textContent = '添加工人';
document.getElementById('workerForm').reset();
document.getElementById('workerModal').style.display = 'flex';
}

// 编辑工人
async function editWorker(id) {
try {
console.log('编辑工人:', id);
const response = await fetch(`/workers/${id}`);

if (!response.ok) {
throw new Error('获取工人数据失败');
}

const worker = await response.json();
currentEditingId = id;

document.getElementById('modalTitle').textContent = '编辑工人';
document.getElementById('name').value = worker.name || '';
document.getElementById('classroom').value = worker.classroom || '';
document.getElementById('teacher').value = worker.teacher || '';
document.getElementById('date').value = formatDateForInput(worker.date);

document.getElementById('workerModal').style.display = 'flex';

} catch (error) {
console.error('编辑工人错误:', error);
showMessage('获取工人数据失败: ' + error.message, 'error');
}
}

// 删除工人
async function deleteWorker(id) {
if (!confirm('确定要删除这个工人吗？此操作不可撤销。')) {
return;
}

try {
const response = await fetch(`/workers/${id}`, {
method: 'DELETE'
});

if (!response.ok) {
throw new Error('删除失败');
}

showMessage('工人删除成功', 'success');
loadWorkers();

} catch (error) {
console.error('删除工人错误:', error);
showMessage('删除失败: ' + error.message, 'error');
}
}

// 搜索工人
function searchWorkers() {
const searchTerm = document.getElementById('searchInput').value.toLowerCase().trim();

if (!searchTerm) {
renderWorkersTable(workers);
return;
}

const filteredWorkers = workers.filter(worker =>
(worker.name && worker.name.toLowerCase().includes(searchTerm)) ||
(worker.classroom && worker.classroom.toString().includes(searchTerm)) ||
(worker.teacher && worker.teacher.toLowerCase().includes(searchTerm))
);

renderWorkersTable(filteredWorkers);
}

// 清空搜索
function clearSearch() {
document.getElementById('searchInput').value = '';
renderWorkersTable(workers);
}

// 关闭模态框
function closeModal() {
document.getElementById('workerModal').style.display = 'none';
currentEditingId = null;
}

// 退出登录
async function logout() {
try {
const response = await fetch('/api/logout', { method: 'POST' });
window.location.href = '/login.html';
} catch (error) {
console.error('退出登录错误:', error);
window.location.href = '/login.html';
}
}

// 工具函数
function formatDate(dateString) {
if (!dateString) return '';
try {
const date = new Date(dateString);
return date.toLocaleDateString('zh-CN');
} catch (e) {
return dateString;
}
}

function formatDateForInput(dateString) {
if (!dateString) return '';
try {
const date = new Date(dateString);
return date.toISOString().split('T')[0];
} catch (e) {
return '';
}
}

function showLoading() {
const tbody = document.getElementById('workersTableBody');
tbody.innerHTML = `
<tr>
    <td colspan="6" class="loading">
        <div class="spinner"></div>
        <span style="margin-left: 10px;">加载中...</span>
    </td>
</tr>
`;
}

function hideLoading() {
// 加载状态会在renderWorkersTable中被替换
}

function showMessage(message, type) {
const messageDiv = document.getElementById('message');
messageDiv.textContent = message;
messageDiv.className = `message ${type}`;
messageDiv.style.display = 'block';

setTimeout(() => {
messageDiv.style.display = 'none';
}, 5000);
}
</script>
    </body>
</html>